//
//  PictureSelectorViewController.swift
//  Weobo
//
//  Created by 史亚洲 on 16/1/26.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SnapKit

private let reuseIdentifier = "Cell"
private let selectorCellmargin: CGFloat = 5
private let rowCount: CGFloat = 4
private let maxImageCount = 9

class PictureSelectorViewController: UICollectionViewController {

    //存放图片的数组
     lazy var imageList = [UIImage]()
    
    //构造方法
    init(){
        let w = (KWidth-(rowCount+1) * selectorCellmargin)/rowCount
        let flowLayout=UICollectionViewFlowLayout()
        
        //设置itemSize
        flowLayout.itemSize=CGSize(width: w, height: w)
        
        //设置间距
        flowLayout.minimumInteritemSpacing=selectorCellmargin
        flowLayout.minimumLineSpacing=selectorCellmargin
        
        //设置sectionInset,即组与组之间的间距
        flowLayout.sectionInset = UIEdgeInsetsMake(selectorCellmargin, selectorCellmargin, 0, selectorCellmargin)
        
        
        //父类构造方法调用完毕,就意味着对象构造完毕
        super.init(collectionViewLayout: flowLayout)
        
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLoad() {
        super.viewDidLoad()

       self.collectionView!.registerClass(PictureSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)

        // Do any additional setup after loading the view.
    }


    // MARK: UICollectionViewDataSource,设置数据源方法
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
       
        let delta = imageList.count == maxImageCount ? 0 : 1
        
        return imageList.count+delta
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PictureSelectorCell
        //cell.backgroundColor=UIColor.randomColor()
        // Configure the cell
        if indexPath.item == imageList.count {
        
        print(indexPath.item,imageList.count)
            
            //不做任何操作
           cell.image=nil
        
        }else {
        
        cell.image=imageList[indexPath.item]
        
        }
        
        //设置代理
        cell.selectorDelegate=self
    
        return cell
    }


}
//3.实现代理方法
extension PictureSelectorViewController: PictureSelectorCellDelegate {
    
    func userWillDeletePicture(cell: PictureSelectorCell) {
        print(__FUNCTION__)
        
            //3.1获取indexPath
        if let indexPath=collectionView?.indexPathForCell(cell){
            
            //3.2删除数据源对应的数据
            imageList.removeAtIndex(indexPath.item)
        
            //3.3刷新集合视图数据
            collectionView?.reloadData()
        }
        
        
        
    }
    func userWillSelectPicture(cell: PictureSelectorCell) {
        print(__FUNCTION__)
        if cell.image != nil {
            print("已经设置图片啦,不要再设置啦")
            return
        }
    
        
        //设置图片,图片选择器为系统的
        let picker = UIImagePickerController()
        
        //设置代理
        picker.delegate=self
        
        //设置允许编辑,以后上传用户头像,可以打开这个设置
        //picker.allowsEditing=true
        
        presentViewController(picker, animated: true, completion: nil)

    }
    
}
extension PictureSelectorViewController: UINavigationControllerDelegate,UIImagePickerControllerDelegate {
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        print(image)
        print("========")
        
        
        //1.编辑信息
        print(editingInfo)
        
        //2.将图片添加到数据源数组中,一旦操作完毕,就必须刷新数据
        imageList.append(image)
        
        //3.刷新页面
        collectionView?.reloadData()
        
        //4.实现完这个方法后,需要自己dismiss
        dismissViewControllerAnimated(true, completion: nil)
        
    }




}
//1.声明协议,协议方法
protocol  PictureSelectorCellDelegate: NSObjectProtocol {
    //1.1用户选择图片
    func userWillSelectPicture(cell: PictureSelectorCell)
    
    //1.2用户删除图片
    func userWillDeletePicture(cell: PictureSelectorCell)

}

//2.声明协议属性
class PictureSelectorCell: UICollectionViewCell {
   
    
    //2.1定义外部的变量
    weak var selectorDelegate: PictureSelectorCellDelegate?
    
    
    //定义外部属性
    var image: UIImage? {
    
        didSet {
        deleteBtn.hidden=(image==nil)
        addBtn.setImage(image, forState: .Normal)
        
        
        }
    
    
    }
    
    //2.2监听方法
    @objc private func addBtnClick() {
    
        //使用代理调用协议方法
        selectorDelegate?.userWillSelectPicture(self)
    
    }
    
    @objc private func deleteBtnClick() {
        
        
        selectorDelegate?.userWillDeletePicture(self)
    }
    
    //找到自定义入口
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    //MARK:2.设置UI视图
    private func setupUI() {
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        
        //设置约束
        addBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
    
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(addBtn.snp_top)
            make.right.equalTo(addBtn.snp_right)
        }
    
        //添加点击事件
        addBtn.addTarget(self, action: "addBtnClick", forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: "deleteBtnClick", forControlEvents: .TouchUpInside)
    
    }
    
    

    //MARK:1.懒加载视图
    //添加按钮
    private lazy var addBtn: UIButton=UIButton(imageName: nil, backImageName: "compose_pic_add")
    
    //删除按钮
    private lazy var deleteBtn: UIButton=UIButton(imageName: "compose_photo_close", backImageName: nil)



}
